package com.itheima.springboottlias.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.springboottlias.common.utils.JwtUtils;
import com.itheima.springboottlias.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("=====初始化=====");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        log.info("===做过滤请求===");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//token存在请求头里面
        String token = request.getHeader("Token");
        String url = request.getRequestURI().toString();
//如果是登录则放行
        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (!StringUtils.hasText(token)) {
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
 //响应
            response.getWriter().write(json);
        }
//验证
        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(servletRequest, servletResponse);

        } catch (Exception e) {
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

        }


    }

    @Override
    public void destroy() {
        log.info("==销毁过滤器==");
        Filter.super.destroy();
    }
}
